﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System.IO;
using Admin.Entity;
using System;
using Microsoft.AspNetCore.Hosting;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;

namespace Admin.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UploadController : ControllerBase
    {
        private readonly IWebHostEnvironment env;

        public UploadController(IWebHostEnvironment env)
        {
            this.env = env;
        }

        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult FileForm(IFormFile formFile)
        {
            //图片存储的位置
            string path = Directory.GetCurrentDirectory() + @"\\wwwroot\\Image\\";

            //给图片一个新名称
            string newfilename = DateTime.Now.ToString("yyyyMMddhhmmssff");

            //获取原文件的后缀名
            string exp = Path.GetExtension(formFile.FileName);

            //得到存储文件的路径和后缀名
            string filepath = path + newfilename + exp;

            using(var stram = System.IO.File.Create(filepath))
            {
                formFile.CopyTo(stram);//拷贝上传的图片流
                stram.Flush();//关闭流
            }

            //返回图片的相对路径
            return Ok("Image/" + newfilename + exp);
        }

        /// <summary>
        /// 图片上传2
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult>  PostFileForm(IFormFile formFile)
        {
            //文件夹路径
            var folderpath = $"/Upload/{DateTime.Now.ToString("yyyyMMdd")}";

            //文件路径
            var filePath = $"/{DateTime.Now.ToString("yyyyMMddHHmmssff")}{Path.GetExtension(formFile.FileName)}";

            //创建文件夹
            if (!Directory.Exists($"{env.WebRootPath}{folderpath}"))
            {
                Directory.CreateDirectory($"{env.WebRootPath}{folderpath}");
            }

            using(FileStream file=new FileStream($"{env.WebRootPath}{folderpath}{filePath}", FileMode.OpenOrCreate))
            {
                await formFile.CopyToAsync(file);
            }

            return Ok($"{folderpath}{filePath}");
        }
    }
}
